package com.sunyard.manage.controller;

import com.sunyard.constant.ErrMessageConst;
import com.sunyard.dal.bo.*;
import com.sunyard.dal.bo.device.lock.LockAddBO;
import com.sunyard.dal.bo.device.lock.LockEditorBO;
import com.sunyard.dal.bo.device.lock.LockQueryBO;
import com.sunyard.dal.dto.LockQueryResDTO;
import com.sunyard.dal.entity.Lock;
import com.sunyard.dal.entity.Operator;
import com.sunyard.manage.service.LockService;
import com.sunyard.utils.ExcelOutput;
import com.sunyard.utils.Response.BaseResult;
import com.sunyard.utils.Response.GetResult;
import com.sunyard.utils.manage.DataGrid;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

@Api(tags = "LockController", description = "锁具管理")
@Slf4j
@RestController
@RequestMapping(value = "/lock", method = RequestMethod.POST)
public class LockController {

    @Autowired
    private LockService lockService;

    @RequestMapping(value = "/queryPage", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("分页查询锁具信息")
    public BaseResult<DataGrid<LockQueryResDTO>> getLockByPage(@RequestBody PaginationBO<LockQueryBO> queryBO, HttpServletRequest request) {
        try {
            return lockService.getLockByPage(queryBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/addLock", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("新增终端信息")
    public BaseResult addLock(@Validated @RequestBody LockAddBO addBO, HttpServletRequest request) {
        try {
            return lockService.addLock(addBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/updateLock", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("修改锁具信息")
    public BaseResult<Lock> updateLockinfo(@Validated @RequestBody LockEditorBO lockEditorBO, HttpServletRequest request) {
        try {
            return lockService.updateLock(lockEditorBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/deleteLock", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("删除锁具信息")
    public BaseResult deleteLock(@Validated @RequestBody Lock lock, HttpServletRequest request) {
        try {
            return lockService.deleteLock(lock, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/auditLock", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("审核锁具信息")
    public BaseResult initLock(@RequestBody Lock lock, HttpServletRequest request) {
        try {
            return lockService.audit(lock, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/exportLock", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("锁信息导出")
    public BaseResult exportKey(HttpServletRequest request, HttpServletResponse response) {
        try {
            return lockService.exportLock(request, response);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/selectUserInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("通过所属机构查询柜员id")
    public BaseResult<List<Operator>> selectUserInfo(@RequestBody Lock lock, HttpServletRequest request) {
        try {
            return lockService.selectUserInfo(lock, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/importInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("导入锁数据")
    public BaseResult importInfo(HttpServletRequest request, @RequestParam("multipartFile") MultipartFile multipartFile) {
        try {
            //return lockService.importInfo(file,lockService);
            String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            if (".xls".equals(suffix) || ".xlsx".equals(suffix)) {
                InputStream inputStream = multipartFile.getInputStream();
                HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
//                XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
                HSSFSheet sheet = workbook.getSheetAt(0);
                if (sheet != null) {
                    LockAddBO organizationAddBO = new LockAddBO();
                    // getLastCellNum比列标大1,行标&列标都以0开始。
                    System.out.println(sheet.getLastRowNum() + "==============");
                    for (int i = 1; i < sheet.getLastRowNum(); i++) {
                        // 从第二行开始得到每行的值
                        HSSFRow row = sheet.getRow(i);

                        row.getCell(0).setCellType(CellType.STRING);
                        String lockName = row.getCell(0).getStringCellValue();
                        row.getCell(1).setCellType(CellType.STRING);
                        String orgId = row.getCell(1).getStringCellValue();
                        row.getCell(2).setCellType(CellType.STRING);
                        String lockSn = row.getCell(2).getStringCellValue();
                        row.getCell(3).setCellType(CellType.STRING);
                        String missType = row.getCell(3).getStringCellValue();
                        row.getCell(4).setCellType(CellType.STRING);
                        String isCheck = row.getCell(4).getStringCellValue();
                        row.getCell(5).setCellType(CellType.STRING);
                        String reversion = row.getCell(5).getStringCellValue();
                        row.getCell(6).setCellType(CellType.STRING);
                        String remark = row.getCell(6).getStringCellValue();
                        row.getCell(7).setCellType(CellType.STRING);
                        String lockTyle = row.getCell(7).getStringCellValue();
                        //赋值
                        organizationAddBO.setLockName(lockName);
                        organizationAddBO.setOrgId(orgId);
                        organizationAddBO.setLockSn(lockSn);
                        organizationAddBO.setMissionType(missType);
                        organizationAddBO.setLockType(lockTyle);
                        organizationAddBO.setIsCheck(isCheck);
                        organizationAddBO.setReversion(reversion);
                        organizationAddBO.setRemark(remark);
                        lockService.addLock(organizationAddBO, request);
                    }
                }
                return GetResult.getResultSuccess("导入成功");

            } else {
                return GetResult.getResultFail("文件类型只支持.xls 与.xlsx");
            }

        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    /**
     * 下载导入模板xls
     */
    @ApiOperation("下载导入模板xls")
    @PostMapping("/downloadTem")
    public void downloadTem(HttpServletResponse response) {

        String[] headers = new String[]{"名称", "机构", "锁编号", "场景类型", "复核状态", "日志翻转", "备注", "锁类型"};
        List<Object[]> dataList = null;
        // 防止中文乱码
        String headStr = null;
        OutputStream out = null;
        try {
            headStr = "attachment; filename=\"" + new String("customerMangerTemplate.xls".getBytes("utf8"), "ISO8859-1") + "\"";
            response.setContentType("octets/stream");
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-Disposition", headStr);
            out = response.getOutputStream();
            ExcelOutput ex = new ExcelOutput("customerMangerTemplate.xls", headers, dataList);
            ex.export(out);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
